package core.tool.template.freemarker;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;

public class FreemarkerUtil {
	
	private Configuration cfg=null;
	
	private Template temp=null;
	
	private Map root=new HashMap();
	
	public FreemarkerUtil(String directoryPath,String ftlName,Map root) {
		init(directoryPath,ftlName,root);
	}
	
	public void init(String directoryPath,String ftlName,Map root) {
	    try {
			cfg = new Configuration();
			cfg.setDirectoryForTemplateLoading(new File(directoryPath));
			cfg.setDefaultEncoding("UTF-8"); 
			cfg.setObjectWrapper(new DefaultObjectWrapper());
			temp = cfg.getTemplate(ftlName);
			temp.setEncoding("UTF-8");
			if(root!=null) {
				this.root = root;
			}
		} catch (IOException e) {
			temp=null;
			e.printStackTrace();
		}
	}
	
	public String getTemplateStr() {
		String result="";
		Writer out=new StringWriter();
		processToWriter(out);
		result=out.toString();
		return result;
	}
	
	public boolean processToWriter(Writer out) {
		boolean flag=true;
		try {
			temp.process(root, out);
		} catch (Exception e1) {
			flag=false;
			e1.printStackTrace();
		}	
		return flag;
	}
	
	public void puttoroot(Object o1,Object o2) {
		this.root.put(o1, o2);
	} 

}
